package com.ethink.mdm.facade.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ethink.mdm.api.CountryPortFacade;
import com.ethink.mdm.api.info.CountryPortInfo;
import com.ethink.mdm.api.info.CountryPortPortInfo;
import com.ethink.mdm.api.response.CountryPortCountryInfoTreeResponse;
import com.ethink.mdm.common.mapper.CountryPortQueryMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * countryPort Facade接口
 *
 * @author 辉辉 2022/12/19 10:57
 */
@RestController
@Slf4j
@RequestMapping("mdm-service/facade/v1/countryPort")
public class CountryPortFacadeImpl implements CountryPortFacade {

    @Autowired
    private CountryPortQueryMapper countryPortQueryMapper;

    @Override
    public List<CountryPortCountryInfoTreeResponse> listCountryPort() {
        List<CountryPortCountryInfoTreeResponse> res = new ArrayList<>();
        // 港口树结构
        List<CountryPortInfo> countryPortInfoList = countryPortQueryMapper.selectCountryPortCountryList();
        // 查询所有的港口集合
        // 收集国家集合
        List<String> countryCodeList = countryPortInfoList.stream().map(CountryPortInfo::getCountryCode).collect(Collectors.toList());
        // 查询所有的
        List<CountryPortInfo> portList = countryPortQueryMapper.selectList(Wrappers.<CountryPortInfo>lambdaQuery()
                .in(CountryPortInfo::getCountryCode, countryCodeList)
        );
        // 封装国家
        countryPortInfoList.forEach(countryPortInfo -> {
            CountryPortCountryInfoTreeResponse countryPortCountryInfoTreeResponse = new CountryPortCountryInfoTreeResponse();
            BeanUtil.copyProperties(countryPortInfo, countryPortCountryInfoTreeResponse, true);
            res.add(countryPortCountryInfoTreeResponse);
        });
        // 封装港口
        res.forEach(country -> {
            List<CountryPortPortInfo> countryPortList = new ArrayList<>();
            portList.forEach(port -> {
                if (port.getCountryCode().equals(country.getCountryCode())) {
                    CountryPortPortInfo countryPortPortInfo = new CountryPortPortInfo();
                    BeanUtil.copyProperties(port, countryPortPortInfo, true);
                    countryPortList.add(countryPortPortInfo);
                }
            });
            country.setPortList(countryPortList);
        });
        return res;
    }
}
